//
//  MapPreviewViewController.m
//  DTKMapBundle
//
//  Created by mac on 2024/10/21.
//

#import "MapPreviewViewController.h"

#import <Masonry/Masonry.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "SearchMapViewController.h"
#import "DTKMapBundle.h"
#import <MapKit/MapKit.h>
@interface MapPreviewViewController ()

@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *subtitleLabel;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIButton *navigationButton;

@end

@implementation MapPreviewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [AMapServices sharedServices].enableHTTPS = YES;

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回"
                                                                             style:UIBarButtonItemStylePlain
                                                                            target:self
                                                                            action:@selector(returnAction)];
    
    self.navigationItem.title = self.info.address;
    
    self.mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    self.mapView.showsUserLocation = YES;
    self.mapView.zoomLevel = 15;
    [self.view addSubview:self.mapView];
    
    CLLocationCoordinate2D cod = self.info.location.coordinate;
    MAPointAnnotation* ann = [[MAPointAnnotation alloc] init];
    ann.coordinate = CLLocationCoordinate2DMake(cod.latitude, cod.longitude);
    ann.title = self.info.title;
    ann.subtitle = self.info.title;
    
    [self.mapView addAnnotation:ann];
    [self.mapView setCenterCoordinate:ann.coordinate];
    [self setupViews];
    self.titleLabel.text = self.info.title;
    self.subtitleLabel.text = self.info.title;
}

- (void)setupViews {
    [self.view addSubview:self.contentView];
    [self.contentView addSubview:self.titleLabel];
    [self.contentView addSubview:self.subtitleLabel];
    [self.contentView addSubview:self.navigationButton];
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.leading.trailing.equalTo(@0);
        make.height.equalTo(@100);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(@10);
        make.trailing.equalTo(self.navigationButton.mas_leading).offset(-10);
        make.top.equalTo(@10);
    }];
    
    [self.subtitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).offset(5);
        make.trailing.equalTo(self.titleLabel);
        make.leading.equalTo(@10);
    }];
        
    [self.navigationButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@10);
        make.trailing.equalTo(@-20);
        make.width.height.equalTo(@44);
    }];
}

- (void)buttonClick:(UIButton *)sender {
    [self doNavigationWithEndLocation:@[@(self.info.location.coordinate.latitude), @(self.info.location.coordinate.longitude)]];
}

-(void)doNavigationWithEndLocation:(NSArray *)endLocation
{
 NSMutableArray *maps = [NSMutableArray array];
 //苹果原生地图-苹果原生地图方法和其他不一样
 NSMutableDictionary *iosMapDic = [NSMutableDictionary dictionary];
 iosMapDic[@"title"] = @"苹果地图";
 [maps addObject:iosMapDic];
 //百度地图
 if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
  NSMutableDictionary *baiduMapDic = [NSMutableDictionary dictionary];
  baiduMapDic[@"title"] = @"百度地图";
  NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%@,%@|name=北京&mode=driving&coord_type=gcj02",endLocation[0],endLocation[1]] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  baiduMapDic[@"url"] = urlString;
  [maps addObject:baiduMapDic];
 }
 //高德地图
 if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
  NSMutableDictionary *gaodeMapDic = [NSMutableDictionary dictionary];
  gaodeMapDic[@"title"] = @"高德地图";
     NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%@&lon=%@&dev=0&style=2",@"导航功能",@"nav123456",endLocation[0],endLocation[1]] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  gaodeMapDic[@"url"] = urlString;
  [maps addObject:gaodeMapDic];
 }
 //谷歌地图
 if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"comgooglemaps://"]]) {
  NSMutableDictionary *googleMapDic = [NSMutableDictionary dictionary];
  googleMapDic[@"title"] = @"谷歌地图";
     NSString *urlString = [[NSString stringWithFormat:@"comgooglemaps://?x-source=%@&x-success=%@&saddr=&daddr=%@,%@&directionsmode=driving",@"导航测试",@"nav123456",endLocation[0], endLocation[1]] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  googleMapDic[@"url"] = urlString;
  [maps addObject:googleMapDic];
 }
 //腾讯地图
 if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"qqmap://"]]) {
  NSMutableDictionary *qqMapDic = [NSMutableDictionary dictionary];
  qqMapDic[@"title"] = @"腾讯地图";
     NSString *urlString = [[NSString stringWithFormat:@"qqmap://map/routeplan?from=我的位置&type=drive&tocoord=%@,%@&to=终点&coord_type=1&policy=0",endLocation[0], endLocation[1]] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  qqMapDic[@"url"] = urlString;
  [maps addObject:qqMapDic];
 }
 //选择
 UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"选择地图" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
 NSInteger index = maps.count;
 for (int i = 0; i < index; i++) {
  NSString * title = maps[i][@"title"];
  //苹果原生地图方法
  if (i == 0) {
   UIAlertAction * action = [UIAlertAction actionWithTitle:title style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
    [self navAppleMapnavAppleMapWithArray:endLocation];
   }];
   [alert addAction:action];
   continue;
  }
  UIAlertAction * action = [UIAlertAction actionWithTitle:title style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
   NSString *urlString = maps[i][@"url"];
      [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:^(BOOL success) {
          
      }];
  }];
  [alert addAction:action];
 }
 UIAlertAction * action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
 }];
 [alert addAction:action];
    alert.popoverPresentationController.sourceView = [[DTKMapBundle uiHierachyService]currentTopViewController].view;
    alert.popoverPresentationController.sourceRect = [[DTKMapBundle uiHierachyService]currentTopViewController].view.bounds;
    [[[DTKMapBundle uiHierachyService]currentTopViewController] presentViewController:alert animated:YES completion:nil];
}

//苹果地图
- (void)navAppleMapnavAppleMapWithArray:(NSArray*) array
{
 float lat = [NSString stringWithFormat:@"%@", array[0]].floatValue;
 float lon = [NSString stringWithFormat:@"%@", array[1]].floatValue;
 //终点坐标
 CLLocationCoordinate2D loc = CLLocationCoordinate2DMake(lat, lon);
 //用户位置
 MKMapItem *currentLoc = [MKMapItem mapItemForCurrentLocation];
 //终点位置
 MKMapItem *toLocation = [[MKMapItem alloc]initWithPlacemark:[[MKPlacemark alloc]initWithCoordinate:loc addressDictionary:nil] ];
 NSArray *items = @[currentLoc,toLocation];
 //第一个
 NSDictionary *dic = @{       MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving,       MKLaunchOptionsMapTypeKey : @(MKMapTypeStandard),       MKLaunchOptionsShowsTrafficKey : @(YES)
       };
 //第二个，都可以用
 // NSDictionary * dic = @{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,
 //       MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]};
 [MKMapItem openMapsWithItems:items launchOptions:dic];
}

- (void)returnAction {
    [self.navigationController popViewControllerAnimated: YES];
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font = [UIFont systemFontOfSize:18];
        _titleLabel.textColor = [UIColor blackColor];
    }
    return  _titleLabel;
}

- (UILabel *)subtitleLabel {
    if (!_subtitleLabel) {
        _subtitleLabel = [[UILabel alloc] init];
        _subtitleLabel.font = [UIFont systemFontOfSize:15];
        _subtitleLabel.textColor = [UIColor grayColor];
    }
    return  _subtitleLabel;
}

- (UIView *)contentView {
    if (!_contentView) {
        _contentView = [[UIView alloc] init];
        _contentView.backgroundColor = [UIColor whiteColor];
    }
    return  _contentView;
}

- (UIButton *)navigationButton {
    if (!_navigationButton) {
        _navigationButton = [UIButton buttonWithType: UIButtonTypeCustom];
        NSString *strResourcesBundle = [[NSBundle mainBundle] pathForResource:@"DTKMapBundle" ofType:@"bundle"];
        NSString *strC = [[NSBundle bundleWithPath:strResourcesBundle] pathForResource:@"daohang" ofType:@"png"];
        UIImage *imgC = [UIImage imageWithContentsOfFile:strC];
        [_navigationButton setImage:imgC forState:UIControlStateNormal];
//        [_navigationButton setImage:[UIImage imageNamed:@"daohang"] forState:UIControlStateNormal];
        [_navigationButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _navigationButton;
}

@end
